package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.XinXiaoRongParam;
import com.block.source.model.api.XinYongPaiParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class XinYongPaiReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret().substring(0, 16);
        String apiKey = sourceBaseInfo.getApiKey();

        JSONObject jsonObject = JSONObject.parseObject(paramContent);
        if (jsonObject.isEmpty()){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("name")) || StrUtil.isEmpty(jsonObject.getString("phone")) || StrUtil.isEmpty(jsonObject.getString("cityName")) || StrUtil.isEmpty(jsonObject.getString("domainFrom"))){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        if (!jsonObject.getString("domainFrom").equals(apiKey)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的渠道编号不符"));
            return sourceApiResult;
        }

        XinYongPaiParam xinYongPaiParam = JSON.parseObject(paramContent, XinYongPaiParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContent);


        // 通过城市编码,获取城市信息
//        AddressInfo addressInfo = addressInfoService.getAddresInfoByCity(userDataParam.getCity());
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());
        userDataParam.setRealName("默认");
        userDataParam.setMobileMd5(xinYongPaiParam.getPhone());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret().substring(0, 16);
        String apiKey = sourceBaseInfo.getApiKey();

        JSONObject jsonObject = JSONObject.parseObject(paramContent);
        if (jsonObject.isEmpty()){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        if (!jsonObject.getString("domainFrom").equals(apiKey)){
            sourceApiResult.setReturnObject(this.getError("进件传入的渠道编号不符"));
            return sourceApiResult;
        }

        XinYongPaiParam xinYongPaiParam = JSON.parseObject(paramContent, XinYongPaiParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContent);

        userDataParam.setMobile(xinYongPaiParam.getPhone());
        userDataParam.setRealName(xinYongPaiParam.getName());

        String productId = xinYongPaiParam.getParams().getString("productId");
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), productId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 0);
        returnObject.put("message", "匹配成功！");
        returnObject.put("data", false);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("productId",pushResultInfo.getOutOrderNo());
        returnObject.put("params", jsonObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                returnObject.put("data",true);
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        returnObject.put("data",false);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("message", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 0);
        returnObject.put("message", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        XinYongPaiParam xinYongPaiParam = JSON.parseObject(paramContent, XinYongPaiParam.class);

        UserDataParam userDataParam = new UserDataParam();

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

//        userDataParam.setMobileMd5(xinYongPaiParam.getPhone());
//        userDataParam.setMobile(xinYongPaiParam.getPhone());
//        userDataParam.setRealName(xinYongPaiParam.getName());


        if (StringUtils.isEmpty(xinYongPaiParam.getSex())){
            userDataParam.setSex("0");
        }else if ("0".equals(xinYongPaiParam.getSex())){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }

        if (xinYongPaiParam.getAge() == null){
            userDataParam.setAge(30);
        }else {
            userDataParam.setAge(xinYongPaiParam.getAge());
        }

        userDataParam.setCity(xinYongPaiParam.getCityName());
        userDataParam.setCityCode(xinYongPaiParam.getCityCode());


        String custQualificationTag = xinYongPaiParam.getCustQualificationTag();
        if (StringUtils.isNotEmpty(custQualificationTag)){
            if (custQualificationTag.contains(",")){
                String[] split = custQualificationTag.split(",");
                for (String s : split) {
                    userDataParam = this.all(s,userDataParam);
                }
            }else {
                userDataParam = this.all(custQualificationTag,userDataParam);
            }
        }

        userDataParam = this.addOthers(userDataParam);

        if (StringUtils.isEmpty(xinYongPaiParam.getCustIp())){
            userDataParam.setUserIp("127.0.0.1");
        }else {
            userDataParam.setUserIp(xinYongPaiParam.getCustIp());
        }

        String loan = xinYongPaiParam.getAppamt();
        if (StringUtils.isEmpty(loan)){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        }else if (Integer.valueOf(loan) >= Integer.valueOf("1") && Integer.valueOf(loan) < Integer.valueOf("3")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (Integer.valueOf(loan) >= Integer.valueOf("3") && Integer.valueOf(loan) < Integer.valueOf("5")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (Integer.valueOf(loan) >= Integer.valueOf("5") && Integer.valueOf(loan) < Integer.valueOf("10")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (Integer.valueOf(loan) >= Integer.valueOf("10") && Integer.valueOf(loan) < Integer.valueOf("20")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        String sesameSeed = xinYongPaiParam.getSesameSeed();
        if ("2".equals(sesameSeed)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if ("1".equals(sesameSeed)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if ("0".equals(sesameSeed)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else{
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }

        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());


        return userDataParam;
    }

    public static UserDataParam all(String storey,UserDataParam userDataParam){
        switch (storey) {
            case "0":
                userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
                break;
            case "1":
                userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
                break;
            case "2":
                userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
                break;
            case "3":
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
                break;
            case "4":
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
                break;
            case "5":
                userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
                break;
            case "6":
                userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
                break;
            case "11":
                userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
                break;
            case "12":
                userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt002.getValue());
                break;
            case "13":
                userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
                break;
            default:
                break;
        }
        return userDataParam;
    }

    public static UserDataParam addOthers(UserDataParam userDataParam){
        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());

        if (StringUtils.isEmpty(userDataParam.getHouse())){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getCar())){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getBaoxian())){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getGongzuo())){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getGjj())){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getShebao())){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getXinyongka())){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getBaitiao())){
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        }
        if (StringUtils.isEmpty(userDataParam.getYuqi())){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }

        return userDataParam;
    }

}
